<template>
    <div class="table">
        <div class="actions">
            <a-upload v-if="!storeGroupCode" :showUploadList="false" :action="importStoreInventory" @change="handleChange">
                <a-button class="mr-10" type="primary">批量导入</a-button>
            </a-upload>
            <a-button type="primary" v-if="storeGroupCode" class="ml-20" @click="continueImport">批量导入</a-button>
            <a-button type="primary" class="ml-20" @click="downTemplate">下载模板</a-button>
        </div>
        <p>每次导入以最后一次导入的数据为准</p>
        <a-input-search placeholder="请输入关键字" v-model="search" enter-button="搜索" size="large"
            @search="onSearch">
        </a-input-search>
        <a-table style="margin-top: 20px" bordered @change="handleTableChange" :columns="columns" :rowKey="record => record.id"
            :data-source="storeList" :pagination="pagination">
            <span slot="action" slot-scope="text, record">
                <a-button @click="remove(record.id)" type="link">删除</a-button>
            </span>
        </a-table>
        <a-modal v-model="showModal" title="提示">
          <template slot="footer">
            <a-button key="back" @click="showModal = false">
              取消
            </a-button>
            <a-upload class="ml-20" key="submit" :data="params" :showUploadList="false" :action="importStoreInventory" @change="handleChange">
                <a-button class="mr-10" type="primary">批量导入</a-button>
            </a-upload>
          </template>
          <div>
            <a-radio-group :options="plainOptions" :default-value="radioValue"  @change="radioChange" />
          </div>
        </a-modal>
    </div>
</template>

<script>
import {
    downTemplate,
    importStoreInventory,
    queryStores,
    deleteStore,
    downErrorStore
} from "@/api/micromall/storePackage";
const columns = [
    {
        dataIndex: "storeCode",
        title: "店仓编号",
    },
    {
        title: "店仓名称",
        dataIndex: "storeName",
    },
    {
        title: "操作",
        key: "action",
        scopedSlots: { customRender: "action" },
    },
];
export default {
    name: "",
    props: {
        value: {
            type: String
        },
    },
    data() {
        return {
            storeList: [],
            columns,
            searchText: "",
            importStoreInventory,
            pagination: {
                current: 1,
                pageSize: 10,
                pageSizeOptions: ["10", "20", "30"],
                showTotal: (total, range) => {
                    return range[0] + "-" + range[1] + " 共" + total + "条";
                },
                showQuickJumper: true,
                showSizeChanger: true,
                total: 0,

            },
            storeGroupCode: undefined,
            search:'',
            showModal: false,
            plainOptions: [
              { label: '覆盖原数据', value: 'cover' },
              { label: '增加数据', value: 'add' },
            ],
            radioValue:'cover'
        };
    },
    components: {

    },
    watch: {
        value(n) {
            if (n) {
                console.log(n)
                this.storeGroupCode = n
                this.queryList()
            }
        },
    },
    computed:{
      params:function(){
        const { storeList, radioValue, storeGroupCode } = this
        return storeList.length > 0 && radioValue == 'add' ? { storeGroupCode } : null
      }
    },
    methods: {
      handleCancel(){

      },
      handlerData(){

      },
      continueImport(){
        this.showModal = true
      },
      radioChange(e){
        this.radioValue = e.target.value
      },
        handleTableChange(pagination) {
            this.pagination = pagination
            this.queryList()
        },
        uploadChange({ file }) {
            if (file.status == "uploading") {
                this.spinning = true;
            }
            if (file.status == "done") {
                this.spinning = false;
                this.handleResponse(file.response)
                console.log(file.response)
                // this.storeGroupCode = file.response.data.storeGroupCode;
                // this.queryList();
            }
        },
        handleChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList)
            }
            if (info.file.status === 'done') {
                const { msg, message, code, data } = info.file.response
                if (code == 200) {
                    const { storeGroupCode, wrongNumber, successNum, failureNum } = data
                    this.storeGroupCode = storeGroupCode
                    this.showModal = false
                    this.$emit('change', storeGroupCode);
                    this.queryList()
                    const len = failureNum.length
                    if (len > 0) {
                        let storeStr =  failureNum.slice(0,8).join()
                        const str = len > 8 ? storeStr + '...' : storeStr
                        this.$confirm({
                            title: '',
                            content: `共成功导入${successNum}条数据,${wrongNumber}条数据有误（点击下载完整数据）${str}`,
                            okText: '下载数据',
                            cancelText: '取消',
                            onOk: (res) => {
                                console.log(res)
                                const url = downErrorStore + storeGroupCode
                                console.log('down',url)
                                window.open(url)
                            }
                        })
                    }else{
                        this.$message.success('导入成功')
                    }
                } else {
                    this.$message.error(msg || message)
                }
            } else if (info.file.status === 'error') {
                this.$message.error(`${info.file.name} file upload failed.`)
            }
        },
        async remove(id) {
            const res = await deleteStore(id);
            if (res.code == 200) {
                this.$message.success("删除成功");
                this.queryList();
            } else {
                this.$message.error(res.msg);
            }
        },
        async queryList() {
            const { storeGroupCode, search, pagination: { current, pageSize: size } } = this;
            console.log(storeGroupCode)
            if (!storeGroupCode) return
            const res = await queryStores({ storeGroupCode, search, current, size });
            if (res.code == 200) {
                const { records, total } = res.data
                this.storeList = records;
                if (total) {
                    this.pagination.total = total
                }
                if (total == 0) {
                    // this.storeGroupCode = undefined
                    this.$emit('change', undefined);
                }else{
                    this.$emit('change', storeGroupCode);

                }
            }
            console.log(res);
        },
        onSearch(e) {
            // this.
             this.queryList()
        },
        inputChangeHandle(e) {
            console.log(e);
        },
        downTemplate() {
            console.log(downTemplate);
            window.open(downTemplate);
        },
    },
};
</script>

<style scoped>
.ml-20 {
    margin-left: 20px;
}

.pt-20 {
    padding-top: 20rpx;
}
</style>
